package com.training.bt.util;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.dampcake.bencode.Bencode;
import com.dampcake.bencode.Type;

public class TorrentUtils {
    private static final Bencode BENCODE = new Bencode(StandardCharsets.ISO_8859_1);

    // 安全修改 announce URL 不改变文件结构
    public static byte[] modifyAnnounce(byte[] torrentBytes, String passkey) {
        try {
            // 解码为嵌套字典结构
            Map<String, Object> torrentMap = BENCODE.decode(torrentBytes, Type.DICTIONARY);

            String encodedPasskey = URLEncoder.encode(passkey, StandardCharsets.UTF_8);
            String newAnnounce = "http://192.168.153.1:6969/announce?passkey=" + encodedPasskey;
            // 只修改顶层 announce 字段
            torrentMap.put("announce", newAnnounce);

            // 特殊处理 info 字典中的 pieces 字段
            if (torrentMap.containsKey("info")) {
                Object infoObj = torrentMap.get("info");
                if (infoObj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> infoMap = (Map<String, Object>) infoObj;

                    // 确保 pieces 保持原始字节数组形式
                    if (infoMap.containsKey("pieces")) {
                        Object pieces = infoMap.get("pieces");
                        if (pieces instanceof String) {
                            // 转换字符串回原始字节
                            byte[] piecesData = ((String) pieces).getBytes(StandardCharsets.ISO_8859_1);
                            infoMap.put("pieces", piecesData);
                        }
                    }
                }
            }

            // 使用相同字符集重新编码
            return BENCODE.encode(torrentMap);
        } catch (Exception e) {
            throw new RuntimeException("修改 torrent 文件失败", e);
        }
    }
}